package com.pmcc.core.service;


import com.pmcc.cj.entity.CjCustomer;
import com.pmcc.cj.entity.vo.CustomerVo;
import com.pmcc.cj.repository.CjCustomerRepository;
import com.pmcc.core.entity.Dict;
import com.pmcc.core.entity.Employee;
import com.pmcc.core.entity.SmsRecord;
import com.pmcc.core.repository.DictRepository;
import com.pmcc.core.repository.EmployeeRepository;
import com.pmcc.core.repository.SmsRecordRepository;
import com.pmcc.core.vo.UserVo;
import com.pmcc.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * Created by tomas on 18/4/9.
 */
@Service
@Transactional
public class EmployeeService {
    @Autowired
    EmployeeRepository employeeRepository;
    @Autowired
    CjCustomerRepository cjCustomerRepository;
    @Autowired
    SmsRecordRepository smsRecordRepository;
    @Autowired
    DictRepository dictRepository;

    public ResultBean getEmployeeInfo(String type){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        UserVo userVo = new UserVo();
        CustomerVo customerVo = new CustomerVo();
        try {
            if(StringUtil.isEmpty(type)){
                Employee employee = employeeRepository.findOne(OnlineUser.getEmployeeId());
                userVo.setUserId(employee.getId());
                userVo.setName(employee.getName());
                userVo.setAvatar(employee.getAvatar());
                resultBean.setObject(userVo);
                return resultBean;
            }else {
                CjCustomer customer = cjCustomerRepository.findOne(OnlineUser.getEmployeeId());
                if(customer != null && "0".equals(customer.getEnabled()) && customer.getDelFlag() == 0){
                    BeanUtils.copyProperties(customer,customerVo);
                    List<Dict> lt= dictRepository.findByCode("JS");
                    String robot = lt.get(0).getName();//5元
                    customerVo.setRobotSet(new BigDecimal(robot));
                    resultBean.setObject(customerVo);
                    return resultBean;
                }
            }
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public ResultBean queryByPage(AntdPage antdPage, Employee model){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            Page page = employeeRepository.findAll(this.getSpecifition(model), antdPage.getPageRequest());
            resultBean.setPage(antdPage.getDefaultCurrent());
            resultBean.setTotal(page.getTotalElements());
            resultBean.setPageSize(antdPage.getPageSize());
            resultBean.setRows(page.getContent());
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public Specification<Employee> getSpecifition(Employee model) {
        return new Specification<Employee>() {
            @Override
            public Predicate toPredicate(Root<Employee> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder builder) {
                List<Predicate> list = new ArrayList<>();
//                if(StringUtil.isNotEmpty(model.getCardName())){
//                    list.add(builder.like(root.get("cardName").as(String.class),  "%"+model.getCardName().trim()+"%"));
//                }
                list.add(builder.equal(root.get("delFlag").as(Integer.class), 0));
//                if (model.getIds() != null && model.getIds().size() > 0) {
//                    CriteriaBuilder.In in = builder.in((root.get("sysOrgId").as(String.class)));
//                    for (String a : model.getIds()) {
//                        in.value(a);
//                    }
//                    list.add(in);
//                }
                Predicate[] p = new Predicate[list.size()];
                return builder.and(list.toArray(p));
            }
        };
    }

    public ResultBean addEmployee(Employee employee){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            Employee e = employeeRepository.findByUserName(employee.getUserName());
            if (e != null) {
                resultBean.setResultCode(ResultBean.FAIL);
                resultBean.setResultDesc("该用户已存在");
                return resultBean;
            }
            //判断是否是业务员
            if("40288043751ac0df01751ae43f7f0000".equals(employee.getRoleId())){
                employee.setSaleMan(true);
            }else {
                employee.setSaleMan(false);
            }
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            employee.setCreateTime(new Date());
            employee.setDelFlag(0);
            //设置初始密码
            employee.setPassword(encoder.encode("123456"));
            employeeRepository.saveAndFlush(employee);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }

    public ResultBean editEmployee(Map map) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            Employee employee = employeeRepository.findOne(map.get("id").toString());
            BeanUtils.setBeanData(employee, map);
            employee.setSaleMan((Boolean) map.get("saleMan"));
            employee=employeeRepository.saveAndFlush(employee);
            System.out.println(employee.getSaleMan());
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }

    public ResultBean deleteEmployee(String id) {
        ResultBean resultBean =new ResultBean(ResultBean.SUCCESS);
        try {
            Employee employee = employeeRepository.findOne(id);
            employee.setDelFlag(1);
            employeeRepository.saveAndFlush(employee);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public ResultBean resetPwd(String employeeId){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            Employee employee = employeeRepository.findOne(employeeId);
            if(employee != null){
                BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
                employee.setPassword(encoder.encode("123456"));
                employeeRepository.saveAndFlush(employee);
            }else {
                resultBean.setResultCode(ResultBean.FAIL);
            }
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public ResultBean resetPassword(@RequestBody Map<String,String> map){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            Employee employee = employeeRepository.findOne(OnlineUser.getEmployeeId());
            String password=map.get("password").toString();//获取输入的密码
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            if(encoder.matches(password,employee.getPassword())){
                String newPassword=map.get("newPassword").toString();//获取新输入的密码
                employee.setPassword(encoder.encode(newPassword));
                employeeRepository.saveAndFlush(employee);
                resultBean.setResultDesc("修改成功!");
            }else{
                resultBean.setResultCode(ResultBean.FAIL);
                resultBean.setResultDesc("原密码输入不正确!");
            }
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }

    public ResultBean cellphoneCode(String cellphone){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            SmsRecord record  = smsRecordRepository.findFirstByTelephoneOrderByCreateTimeDesc(cellphone);
            if(record != null){
                int num = DateUtil.betweenOfMinute(record.getCreateTime(),new Date());
                if(num <=3){
                    resultBean.setResultCode(ResultBean.FAIL);
                    resultBean.setResultDesc("3分钟无法重复获取验证码");
                    return resultBean;
                }
            }
            //生成6为随机数字的验证码
            String str="";
            for(int i=0;i<6;i++){
                int num=(int)(Math.random()*10);
                str+=num;
            }
            String message = "{\"code\":\""+str+"\"}";
            SmsRecord smsRecord=SmsSendUtil.sendSmsCode1(cellphone,message);
            smsRecordRepository.saveAndFlush(smsRecord);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
}
